import logging

from django.contrib.auth import authenticate
from ninja import Form, Router, Schema
from ninja.responses import codes_4xx

from naryad.models import User_sdl
from .models import MyUser

router = Router(tags=["auth"])


class StatusMessage(Schema):
    ok: bool
    status: int
    message: str


class Error(Schema):
    message: str


class MyUserSchema(Schema):
    login: str
    mpp: int
    fam: str
    im: str
    ot: str
    is_active: bool
    is_admin: bool


@router.get(
    "/",
    response={200: list[MyUserSchema], 403: Error(message="Ошибка обработки запроса")},
)
def list_events(request) -> list[MyUserSchema]:  # noqa: ARG001
    return list(MyUser.objects.all())  # type: ignore  # noqa: PGH003
    #     {"login": e.login, "mpp": e.mpp} for e in MyUser.objects.all()
    # ], f"Authenticated user {request.auth}"


# @router.get("/{event_id}")
# def event_details(request, event_id: int):
#     event = MyUser.objects.get(id=event_id)
#     return {"title": event.title, "details": event.details}


class AuthSchemaOut(StatusMessage):
    username: str
    mpp: int
    # doc: int = None
    dolzh: str
    access: str
    fio_short: str


class AuthSchemaIn(Schema):
    username: str
    password: str


@router.post(
    "/login_vue/",
    response={200: AuthSchemaOut, 201: StatusMessage, codes_4xx: StatusMessage},
)
def login_vue(  # noqa: ANN201
    request,
    user_input: Form[AuthSchemaIn],
    # username: Form[str],
    # password: Form[str],
):
    try:
        user: MyUser = authenticate(
            request,
            username=user_input.username,
            password=user_input.password,
        )
        if user is None:
            return 201, {"ok": False, "status": 201, "message": "Неверный логин или пароль"}
        user_auth = User_sdl.objects.get(user=user)
        dolzh = ""
        if len(user_auth.dolzh.split(", ")) > 1:
            dolzh_all = user_auth.dolzh.split(", ")
            if "Старший техник" in dolzh_all:
                dolzh = "Старший техник"
            elif "Зав. ортопедией" in dolzh_all:
                dolzh = "Зав. ортопедией"
        else:
            dolzh2 = user_auth.dolzh
            dolzh = dolzh2[0] if isinstance(dolzh2, list) else dolzh2

        access = ""
        if len(user_auth.access_list()) > 1:
            access_all = user_auth.access_list()
            if "tech_st" in access_all:
                access = "tech_st"
            elif "zav_ort" in access_all:
                access = "zav_ort"
        else:
            access = user_auth.access_list()[0]
        return 200, {
            "ok": True,
            "status": 200,
            "message": "login success user",
            "username": user.login,
            "mpp": user.mpp,
            "dolzh": dolzh,
            "access": access,
            "fio_short": user_auth.fio_short(),
        }
    except Exception:
        logging.exception("Found an error")
        return 201, {"ok": False, "status": 201, "message": "Неверный логин или пароль"}
